package mylab.starters.oss.config.minio;

import io.minio.MinioClient;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import mylab.starters.oss.OssRule;
import mylab.starters.oss.config.OssAutoConfiguration;
import mylab.starters.oss.config.OssProperties;
import mylab.starters.oss.support.minio.MinioTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@AutoConfigureAfter(OssAutoConfiguration.class)
@ConditionalOnProperty(value = MinioAutoConfiguration.PREFIX, havingValue = "true")
public class MinioAutoConfiguration {
    static final public String PREFIX = OssProperties.PREFIX + ".minio.enabled";
    private final OssProperties ossProperties;

    @Bean
    @SneakyThrows
    @ConditionalOnMissingBean
    public MinioClient minioClient() {
        OssProperties.MinioProperties minio = ossProperties.getMinio();
        return MinioClient.builder()
                .endpoint(minio.getEndpoint())
                .credentials(minio.getAccessKey(), minio.getSecretKey())
                .build();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({MinioClient.class, OssRule.class})
    public MinioTemplate minIoTemplate(MinioClient minioClient, OssRule ossRule) {
        return new MinioTemplate(ossProperties.getMinio(), ossRule, minioClient);
    }
}
